import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_business_1907a/bean/cart_info_bean_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvider with ChangeNotifier {
  String cartString = '[]'; //存到sp中的String
  List<CartInfoBeanResult> cartList = []; //从sp中读取到的list

  //存到sp中的方法
  save(goodsId, goodsName, count, price, images) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo'); //获取持久化数据
    //判断cartString是否为空,为空就说明是第一次添加,或者cartInfo被清除了
    //如果有值,进行decode(编码),也就转换操作
    var temp = cartString == null ? [] : json.decode(cartString.toString());
    //把获取到的值转换为list
    List<Map> tampList = (temp as List).cast();
    //声明变量,用于判断购物车中是否存在此商品,通过ID来判断
    var isHave = false;
    int ival = 0; //用于循环的int
    tampList.forEach((element) {
      //进行循环,找出是否已经存在该商品,如果存在,进行数量+1
      if (element['goodsId'] == goodsId) {
        tampList[ival]['count'] = element['count'] + 1;
        cartList[ival].count++;
        isHave = true;
      }
      ival++;
    });

    if (!isHave) {
      Map<String, dynamic> newGood = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images,
      };
      tampList.add(newGood);
      cartList.add(CartInfoBeanResult.fromJson(newGood));
    }

    //把字符串进行encode
    cartString = json.encode(tampList).toString();
    sharedPreferences.setString('cartInfo', cartString);
    notifyListeners();
  }

  //清空购物车的方法
  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove('cartInfo');
    notifyListeners();
  }

  //得到购物车中商品的方法(从String转换为对象)
  getCartInfo() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //获取购物车中的商品,这时是一个字符串
    cartString = sharedPreferences.getString('cartInfo');
    //cartList进行初始化,防止数据混乱
    cartList = [];
    //判断得到的字符串中是否有值
    if (cartString == null) {
      cartList = [];
    } else {
      List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
      tempList.forEach((element) {
        cartList.add(CartInfoBeanResult.fromJson(element));
      });
    }
    print(cartList.length);
    notifyListeners();
  }
}
